<?php

class DigitalPublisher_ArticleProvider
{
	protected static $_dbAdapter;
	
	public function find ($articleId) 
	{
		throw new Exception('Functionality is not implemented yet...');
	}
	
	public function save ( DigitalPublisher_Article $article )
	{
		if (null === $article) {
			throw new Exception('Method save() needs something to save. $article was NULL.');
		}
		
		$data = array();
		$data['title'] = $article->getTitle();
		$data['module_name'] = $article->getModuleName();
		$data['user_id'] = $article->getUserId();
		
		$this->getDbAdapter()->beginTransaction();
		
		try {
			if (null === $article->getArticleId()) {
				$this->getDbAdapter()->insert('article', $data);
				$article->setArticleId( $this->getDbAdapter()->lastInsertId('article') );
			}
			else {
				$this->getDbAdapter()->update('article', $data, array('article_id = ?' => $article->getArticleId()));
			}
			$this->getDbAdapter()->commit();
		}
		catch (Exception $caught) {
			$this->getDbAdapter()->rollBack();
			throw $caught;
		}
		
		return $article;
	}
	
	/**
     * Get the default database adapter for the articles
     * @return Zend_Db_Adapter_Abstract
     * @throws Exception
     */
	public function getDbAdapter() 
    {
    	if(null !== self::$_dbAdapter) {
    		return self::$_dbAdapter;
    	}
    	throw new Exception('No adapter was set. Please set before using.');
    }
    
    /**
     * Set the default database adapter that will be used by all articles
     * @param Zend_Db_Adapter_Abstract $dbAdapter A valid and connected database adapter
     */
    public static function setDbAdapter( Zend_Db_Adapter_Abstract $dbAdapter ) 
    {
    	self::$_dbAdapter = $dbAdapter;
    }
}
